package cn.kgc.springbootdemo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.json.JSONObject;
import cn.kgc.springbootdemo.annotation.LimitRequestAnnotation;
import cn.kgc.springbootdemo.annotation.PassToken;
import cn.kgc.springbootdemo.enums.LimitType;
import cn.kgc.springbootdemo.form.LoginForm;
import cn.kgc.springbootdemo.service.UserService;
import cn.kgc.springbootdemo.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.IOException;

/**
 * <h3>springbootdemo</h3>
 * <p>登录-控制器</p>
 *
 * @author : DongZeJian
 * @date : 2020-05-07 13:33
 **/
@Api(tags = "登录控制器")
@RestController
@RequiredArgsConstructor
@Validated
@Slf4j
public class LoginController {

    private final UserService userService;

    @ApiOperation("获得验证码")
    @GetMapping("/verificationCode")
    @PassToken
    public void verificationCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        //将验证码绑定session
        HttpSession session = request.getSession();
        //设置session保存时间  秒
        session.setMaxInactiveInterval(60*5);
        session.setAttribute("VerifyCode", lineCaptcha.getCode());
        response.setContentType("image/jpeg");
        response.setHeader("Content-Disposition","attachment;filename=test.png");
        //设置响应头
        response.setHeader("Pragma", "no-cache");
        //设置响应头
        response.setHeader("Cache-Control", "no-cache");
        //在代理服务器端防止缓冲
        response.setDateHeader("Expires", 0);
        //输出
        lineCaptcha.write(response.getOutputStream());
        response.getOutputStream().flush();
    }

    @ApiOperation(value = "登录",notes = "登录验证")
    @PostMapping(value = "/doLogin")
    @PassToken
    public R<JSONObject> doLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody @Valid LoginForm login){
        log.info("用户登录：userCode:{},password:{}",login);
        response.setHeader("Access-Control-Allow-Origin","*");
        return R.ok(userService.login(request,response,login));
    }


    /**
     *  退出登录
     *
     * @return
     */
    @ApiOperation(value = "退出登录")
    @GetMapping("/signOut")

    public R<Boolean> signOut(){
        return R.ok(userService.signOut());
    }
}
